import { Component, OnInit, ViewChild, ElementRef, SimpleChanges } from '@angular/core';
import * as OriginChart from "chart.js";
import { isEmptyObject } from "../util";

@Component({
  selector: 'draw-chart',
  templateUrl: 'draw-chart.component.html',
  styleUrls: ['draw-chart.component.less'],
  inputs: ['data']
})
export class DrawChartComponent implements OnInit {
  @ViewChild('canvas', {read: ElementRef})
  canvasEl: ElementRef;
  chartIns;
  config = {
    type: 'line',
    data: {},
    options: {}
  }
  constructor () {}

  ngOnInit () {}

  ngOnChanges (changes: SimpleChanges) {
    let config = changes.data.currentValue
    if (config && !this.chartIns) {
      this.updataChartConfig(config)
      let chart = this.canvasEl.nativeElement;
      this.chartIns = new OriginChart(chart, this.config)
    } else if (config && this.chartIns) {
      this.updataChartConfig(config)
      this.chartIns.update()
    }
  }

  updataChartConfig (payLoad) {
    this.config.type = payLoad.type
    this.config.data = {
      ...payLoad.data
    }
    if (isEmptyObject(this.config.options)) {
      this.config.options = {
        ...payLoad.options
      }
    } else {
      this.config.options.title.text = payLoad.options.title.text
    }
  }
}